import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'controll/location_controller.dart';
import 'flutter_tencent_location_platform_interface.dart';
import 'model/location.dart';

/// An implementation of [FlutterTencentLocationPlatform] that uses method channels.
class MethodChannelFlutterTencentLocation
    extends FlutterTencentLocationPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_tencent_location');

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<String> init(String key) async {
    ///监听native端返回的数据
    methodChannel.setMethodCallHandler((methodCall) async {
      debugPrint(
          'TencentMap:${methodCall.method}  arguments:${methodCall.arguments}');
      switch (methodCall.method) {
        case "flutter_tenc_map_backLocation":
          //返回定位信息
          Location location = Location();
          location.code = methodCall.arguments['code'];
          if (location.code == 200) {
            location.name = await methodCall.arguments['name'];
            location.latitude = await methodCall.arguments['latitude'];
            location.longitude = await methodCall.arguments['longitude'];
            location.address = await methodCall.arguments['address'];
            location.city = await methodCall.arguments['city'];
            location.province = await methodCall.arguments['province'];
            location.area = await methodCall.arguments['area'];
            location.cityCode = await methodCall.arguments['cityCode'];
          }
          if (locationController.listener.isNotEmpty) {
            for (LocationCallBack locationCallBack
                in locationController.listener) {
              locationCallBack(location);
            }
          }
          break;
        case "2":
          break;
      }
    });
    return await methodChannel
        .invokeMethod("flutter_tenc_map_init", {"key": key});
  }

  @override
  void setUserAgreePrivacy() {
    methodChannel.invokeMethod('setUserAgreePrivacy');
  }

  @override
  void stopLocation() {
    methodChannel.invokeMethod("stopLocation");
  }

  @override
  Future<Location?> getLocation(int interval) async {
    var data = await methodChannel.invokeMethod(
        "flutter_tenc_map_getLocation", {"interval": interval.toDouble()});
    print('TencentMap:$data');
    if (data == "error") {
      return null;
    }
    Location location = Location();
    location.name = data['name'];
    location.latitude = data['latitude'];
    location.longitude = data['longitude'];
    location.address = data['address'];
    location.city = data['city'];
    location.province = data['province'];
    location.area = data['area'];
    location.cityCode = data['cityCode'];
    return location;
  }
}
